package com.fxz.security;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fxz.entity.SysUser;
import com.fxz.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author fxz
 * @date 2021/5/10 8:14
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;


    //通过用户名 查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.getByUserName(username);

        if(ObjectUtils.isEmpty(sysUser)){
            throw new UsernameNotFoundException("用户名或密码不正确!");
        }


        return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(),getUserAuthority(sysUser.getId()) );
    }

    /**
     * 获取用户权限信息(角色、菜单权限)
     * @param userId 用户id
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId){

        //角色(ROLE_admin)、菜单权限(sys:user:list)
        String authority = sysUserService.getUserAuthorityInfo(userId); //ROLE_admin,ROLE_normal,sys:user:list,······

        //将逗号分隔的字符串变为授权列表
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
